package com.carnation.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.service.Ftp;
import com.carnation.service.impl.FTPServerImpl;
import com.carnation.service.impl.SFTPServerImpl;
import com.carnation.utils.MenuFileUtril;

public class DownRemoteFileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(DownRemoteFileServlet.class);
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		String path = httpServletRequest.getParameter("path");
		String fileName = httpServletRequest.getParameter("filename");
		MenuFileUtril menuFileUtril = new MenuFileUtril();
		logger.info(path);
		logger.info(fileName);
		Ftp ftp = null;
		if(menuFileUtril.getFTPProtocol().toLowerCase().equals("ftp")){
			ftp = new FTPServerImpl();
		}
		else if(menuFileUtril.getFTPProtocol().toLowerCase().equals("sftp")){
			ftp = new SFTPServerImpl();
		}
		else{
			logger.error("未知协议");
		}
		try {
			String realPath = ftp.getPath(path);
			InputStream is = ftp.findFileStreamByRealPathAndFileName(realPath, fileName);
			if(is == null){
				httpServletResponse.setCharacterEncoding("UTF-8");
				httpServletResponse.getWriter().write("没有找到对应文件");
				httpServletResponse.getWriter().close();
				return ;
			}
			else{
				httpServletResponse.reset();
				httpServletResponse.setContentType("application/x-msdownload");
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + new String (fileName.getBytes("UTF-8"),"ISO-8859-1") + "\"");
				ServletOutputStream out = httpServletResponse.getOutputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				BufferedOutputStream bos = new BufferedOutputStream(out);
				byte[] buff = new byte[1024];
				int i=-1;
				while((i=bis.read(buff))!=-1){
					bos.write(buff,0,i);
				}
				bis.close();
				is.close();
				bos.close();
				out.close();
				logger.info("IP地址为" + httpServletRequest.getRemoteAddr()  + "下载了在目录" + realPath + "下的文件:" + fileName);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
